//
//  DKUnauthorizeProductViewController.m
//  DanKU
//
//  Created by 吴斌 on 2023/9/26.
//

#import "DKUnauthorizeProductViewController.h"
#import "DKUnauthorizedProductStepView.h"
#import "DKUnauthorizedNoRecordView.h"
#import "DKOrderListCell.h"
#import "DKOrderWarnCell.h"
#import <MJRefresh/MJRefresh.h>
#import "DKOrderIssueFailedCell.h"
#import "DKOrderBillsCell.h"
#import "DKOrderBilsHeaderView.h"
#import "DKOrderHisrtoryCell.h"
#import "DKOrderRepayViewController.h"
#import "DKHomeHttp.h"
#import "DKOrderListModel.h"
#import "DKOrderNoDataFootView.h"

@interface DKUnauthorizeProductViewController ()<UITableViewDelegate,UITableViewDataSource,DKOrderWarnCellDelegate>

@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,assign)int offset;
@property (nonatomic,assign)NSInteger orderType;
@property (nonatomic,assign)NSInteger billType;
@property (nonatomic,assign)NSInteger historyType;
@property (nonatomic,assign)NSInteger selectedIndex;
@property (nonatomic,strong)NSMutableArray *orderlist;
@property (nonatomic,strong)NSMutableArray *billsData;
@property (nonatomic,strong)NSMutableArray *historyData;
@property (nonatomic,assign)BOOL isloadTable;
@property (nonatomic,strong)DKOrderListModel *applicatModelData;
@property (nonatomic,strong)DKOrderListModel *billsModeData;
@property (nonatomic,strong)DKOrderListModel *historyModeData;

@property (nonatomic,assign)int Appoffset;
@property (nonatomic,assign)int Billsoffset;
@property (nonatomic,assign)int Histoffset;

@end

@implementation DKUnauthorizeProductViewController

static BOOL initialized = NO;

+ (BOOL)isInitialized {
    return initialized;
}

-(void)viewDidAppear:(BOOL)animated{
    [self getDataSorce:NO];
    if (self.orderType == 1) {
        [self reportData:@"Order"];
    }else if (self.orderType == 2){
        [self reportData:@"Bills"];
    }else{
        [self reportData:@"History"];
    }
}

//-(void)viewWillAppear:(BOOL)animated{
//    [self getDataSorce:NO];
//    if (self.orderType == 1) {
//        [self reportData:@"Order"];
//    }else if (self.orderType == 2){
//        [self reportData:@"Bills"];
//    }else{
//        [self reportData:@"History"];
//    }
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    initialized = YES;
    
    self.view.backgroundColor = DK_Hex(@"#FAFAFA");
    self.orderlist = [NSMutableArray array];
    self.billsData = [NSMutableArray array];
    self.historyData = [NSMutableArray array];
    
    self.selectedIndex = 1;
    self.offset = 1;
    self.orderType = 1;
    //    [self getDataSorce:YES];
    
    self.Appoffset = 1;
    self.Billsoffset = 1;
    self.Histoffset = 1;
}

-(void)getDataSorce:(BOOL)isRefresh{
    NSString * realOrderType = @"";
    
    if (self.orderType == 2) {// 解决 UI排序和接口请求参数问题
        realOrderType = @"3";
        if (!self.billsModeData) {
            self.Billsoffset = 1;
        }else{
            if (self.billsModeData.nextPage != 0 ) {
                self.Billsoffset = self.billsModeData.nextPage;
            }else{
                self.Billsoffset ++;
            }
        }
        self.offset = self.Billsoffset;
    }else if (self.orderType == 3){
        realOrderType = @"2";
        if (!self.historyModeData) {
            self.Histoffset = 1;
        }else{
            if (self.historyModeData.nextPage != 0 ) {
                self.Histoffset = self.historyModeData.nextPage;
            }else{
                self.Histoffset++;
            }
        }
        self.offset = self.Histoffset;
    }else{
        realOrderType = @"1";
        if (!self.applicatModelData) {
            self.Appoffset = 1;
        }else{
            if (self.applicatModelData.nextPage != 0 ) {
                self.Appoffset = self.applicatModelData.nextPage;
            }else{
                self.Appoffset++;
            }
        }
        
        self.offset = self.Appoffset;
    }
    
    if (!isRefresh) {
        self.offset = 1;
    }
    
    [DKPublicHttp apiGetOrderListForAPI:@{@"pageNum":[NSString stringWithFormat:@"%d",self.offset],@"pageSize":@"10",@"type":realOrderType} complete:^(DKOrderListModel * _Nonnull orderlist) {
        if (!self.isloadTable) {// 已经加载过视图
            [self creatUI];
        }
        
        if (!isRefresh) {
            if (self.orderType == 1) {
                [self.orderlist removeAllObjects];
            }else if (self.orderType == 2){
                [self.billsData removeAllObjects];
            }else{
                [self.historyData removeAllObjects];
            }
        }
        
        if (self.orderType == 1) {
            self.applicatModelData = orderlist;
            [self.orderlist addObjectsFromArray:orderlist.orderRecordList];
        }else if (self.orderType == 2){
            self.billsModeData = orderlist;
            [self.billsData addObjectsFromArray:orderlist.orderRecordList];
        }else{
            self.historyModeData = orderlist;
            [self.historyData addObjectsFromArray:orderlist.orderRecordList];
        }
        
        if (orderlist.nextPage == 0) {
            if (isRefresh) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }
        
        [self isRefreshing];
        [self.tableView reloadData];
    }];
}


-(void)creatUI{
    self.isloadTable = YES;
    MJRefreshNormalHeader  *header = [MJRefreshNormalHeader  headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    [header setTitle:@"Dropdown can refresh" forState:MJRefreshStateIdle];
    [header setTitle:@"Release and refresh immediately" forState:MJRefreshStatePulling];
    [header setTitle:@"Refreshing data...." forState:MJRefreshStateRefreshing];
    header.lastUpdatedTimeLabel.hidden = YES;
    self.tableView.mj_header = header;
    
    MJRefreshAutoNormalFooter  *foot = [MJRefreshAutoNormalFooter  footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    foot.stateLabel.hidden = YES;
    foot.refreshingTitleHidden = YES;
    self.tableView.mj_footer = foot;
    self.tableView.mj_footer.ignoredScrollViewContentInsetBottom = DK_SafeAreaBottom ? 34 : 0;
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.view).offset(-DK_SafeAreaTop);
        make.bottom.equalTo(self.view).offset(-DK_IsWidthScale(48)-DK_TabBar_H);
    }];
    UIButton * dk_ProductAgreementBtn = [[UIButton alloc] init];
    [dk_ProductAgreementBtn setTitle:@"《Privacy Agreement》" forState:UIControlStateNormal];
    [dk_ProductAgreementBtn setTitleColor:DK_Hex(@"#CCCCCC") forState:UIControlStateNormal];
    dk_ProductAgreementBtn.titleLabel.font = DK_FONT_Regular(12);
    [dk_ProductAgreementBtn addTarget:self action:@selector(homeCheckAgreement) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:dk_ProductAgreementBtn];
    [dk_ProductAgreementBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.tableView.mas_bottom).offset(DK_IsWidthScale(10));
        make.height.equalTo(@(DK_IsWidthScale(17)));
    }];
    
}
-(void)homeCheckAgreement{
    DKWebViewController * dk_WebViewCtrl = [[DKWebViewController alloc] initWithUrl:DK_PrivacyAgreement withIsNavBar:YES];
    [self.navigationController pushViewController:dk_WebViewCtrl animated:YES];
}

-(void)loadData{
    self.offset = 1;
    [self getDataSorce:NO];
}

-(void)loadMore{
    self.offset ++;
    [self getDataSorce:YES];
}

-(UITableView*)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = DK_Hex(@"#FAFAFA");
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.bounces = YES;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableFooterView = [UIView new];
        [_tableView registerClass:[DKOrderIssueFailedCell class] forCellReuseIdentifier:@"DKOrderIssueFailedCell"];
        [_tableView registerClass:[DKOrderListCell class] forCellReuseIdentifier:@"DKOrderListCell"];
        [_tableView registerClass:[DKOrderBillsCell class] forCellReuseIdentifier:@"DKOrderBillsCell"];
        [_tableView registerClass:[DKOrderHisrtoryCell class] forCellReuseIdentifier:@"DKOrderHisrtoryCell"];
    }
    return _tableView;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.orderType == 1) {
        return 1;
    }else if (self.orderType == 2){
        if (self.billsData.count == 0) {
            return 1;
        }
        return self.billsData.count;
    }else{
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.orderType == 1) {
        return self.orderlist.count;
    }else if (self.orderType == 2){
        return 1;
    }else{
        return self.historyData.count;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.orderType == 1) {
        DKOrderRecordListModel *mode = self.orderlist[indexPath.row];
        if (mode.status == 169) {//放款失败  Issud Faile
            DKOrderIssueFailedCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DKOrderIssueFailedCell" forIndexPath:indexPath];// under review
            cell.dateSouce = mode;
            return cell;
        }else{
            DKOrderListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DKOrderListCell" forIndexPath:indexPath];
            cell.dateSouce = mode;
            return cell;// Approved Rejected Issuing Issued Overdue
        }
    }else if (self.orderType == 2){
        DKOrderBillsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DKOrderBillsCell" forIndexPath:indexPath];
        if (self.billsData.count !=0) {
            DKOrderRecordListModel *mode = self.billsData[indexPath.section];
            //            if (indexPath.section == 0) {
            //                NSLog(@"------%ld",indexPath.section);
            //                cell.isTotal = YES;
            //            }
            cell.dateSouce = mode;
            return cell;
        }else{
            return cell;
        }
    }else{
        DKOrderRecordListModel *mode = self.historyData[indexPath.row];
        DKOrderHisrtoryCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DKOrderHisrtoryCell" forIndexPath:indexPath];
        cell.dateSouce = mode;
        return cell;
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.orderType == 1) {
        DKOrderRecordListModel *mode = self.orderlist[indexPath.row];
        if (mode.status == 169) {//放款失败  Issud Faile
            return 235;
        }else{
            return 150;
        }
        
    }else if (self.orderType == 2){
        if (self.billsData.count == 0) {
            return 0.01;
        }
        //        DKOrderRecordListModel *mode = self.billsData[indexPath.section];
        //        if (indexPath.section == 0) {// 显示 Total Bills
        //            return 135;
        //        }
        //        if (mode.status  == 180) {//部分放款
        //            return 120;
        //        }else{
        return 90;
        //        }
    }else{
        return 151;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if ((self.orderType == 1 && self.orderlist.count == 0) || (self.orderType == 2 && self.billsData.count == 0) || (self.orderType == 3 && self.historyData.count == 0)) {
        return 260;
    }
    if (section == 0) {
        if (self.orderType == 2) {
            return 260+62+40;
        }else{
            return 260+62;
        }
    }else{
        return 0.01;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        DKOrderWarnCell *headView = [[DKOrderWarnCell alloc] init];
        if (self.orderType == 2) {
            headView.frame = CGRectMake(0, 0,DK_SCREEN_W , 260+62+40);
            headView.dk_totalbilview.hidden = NO;
        }else{
            headView.frame = CGRectMake(0, 0,DK_SCREEN_W , 260+62);
            headView.dk_totalbilview.hidden = YES;
        }
        if ((self.orderType == 1 && self.orderlist.count == 0) || (self.orderType == 2 && self.billsData.count == 0) || (self.orderType == 3 && self.historyData.count == 0)) {
            headView.dk_WarnCellView.hidden  = YES;
        }else{
            headView.dk_WarnCellView.hidden  = NO;
        }
        headView.Type = self.orderType;
        headView.delegate = self;
        return headView;
    }
    
    UIView *headerView = [[UIView alloc] init];
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if ((self.orderType == 1 && self.orderlist.count == 0) || (self.orderType == 2 && self.billsData.count == 0) || (self.orderType == 3 && self.historyData.count == 0)) {
        return DK_SCREEN_H-300;
    }
    if (self.orderType == 2) {
        DKOrderRecordListModel *mode = self.billsData[section];
        if (mode.status == 180) {//订单逾期
            return 40;
        }
    }
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if ((self.orderType == 1 && self.orderlist.count == 0) || (self.orderType == 2 && self.billsData.count == 0) || (self.orderType == 3 && self.historyData.count == 0)) {
        self.tableView.mj_footer.hidden = YES;
        DKOrderNoDataFootView *headView = [[DKOrderNoDataFootView alloc] initWithFrame:CGRectMake(0, 0,DK_SCREEN_W , DK_SCREEN_H-300)];
        return headView;
    }else{
        self.tableView.mj_footer.hidden = NO;
    }
    
    if (self.orderType == 2) {
        DKOrderRecordListModel *mode = self.billsData[section];
        if (mode.status == 180) {//订单逾期
            DKOrderBilsHeaderView *headView = [[DKOrderBilsHeaderView alloc] initWithFrame:CGRectMake(0, 0,DK_SCREEN_W , 40)];
            return headView;
        }
    }
    UIView *footView = [[UIView alloc] init];
    return footView;
}

-(void)isRefreshing{
    if ([self.tableView.mj_header isRefreshing]) {
        [self.tableView.mj_header endRefreshing];
    }
    if ([self.tableView.mj_footer isRefreshing]) {
        [self.tableView.mj_footer endRefreshing];
    }
}


#pragma mark DKOrderWarnCellDelegate
-(void)DKOrderWarnSelectedDelegate:(NSInteger)selected{
    if (self.selectedIndex == selected) {
        return;
    }
    //    if(self.orderType == selected){
    //        return;
    //    }
    //
    self.orderType = selected;
    //    if (self.billType == 0 && selected == 2) {
    //        [self getDataSorce:NO];
    //    }
    //
    //    if (self.historyType == 0  && selected == 3) {
    //        [self getDataSorce:NO];
    //    }
    //
    self.selectedIndex = selected;
    [self getDataSorce:NO];
    
    NSString  *submitTpye = @"";
    
    switch (selected) {
        case 1:{// Application
            submitTpye = @"Order";
        }
            break;
        case 2:{// My bills
            self.billType = 2;
            submitTpye = @"Bills";
        }
            break;
        case 3:{// History
            self.historyType = 3;
            submitTpye = @"History";
        }
            break;
            
        default:
            break;
    }
    [self.tableView reloadData];
    
    [self reportData:submitTpye];
}

-(void)reportData:(NSString*)submitTpye{
    [DKPublicHttp apiUserBrhavRecordForAPI:@{@"type":submitTpye} withPageName:DK_Orders withAction:DK_ActionEnter complete:^{
        
    } fail:^{
        
    }];
}



@end
